<?php
/**
 * Created by PhpStorm.
 * User: joe
 * Date: 17-11-16
 * Time: 下午4:47
 */

namespace System;

class Crypt {

    private $key = '071642fa72ba780ee90ed36350d82745';

    public function __construct($key = null) {
        $key ? $this->key = $key : null;
    }

    public function md5($str) {
        $code = substr(md5($str), 10);
        $code .= substr(sha1($str), 0, 28);
        $code .= substr(md5($str), 0, 22);
        $code .= substr(sha1($str), 16) . md5($str);
        $code = md5($code);
        return $code;
    }


    private final static function keyED($txt, $encrypt_key) {
        $encrypt_key = md5($encrypt_key);
        $ctr = 0;
        $tmp = "";
        for ($i = 0; $i < strlen($txt); $i++) {
            if ($ctr == strlen($encrypt_key)) $ctr = 0;
            $tmp .= substr($txt, $i, 1) ^ substr($encrypt_key, $ctr, 1);
            $ctr++;
        }
        return $tmp;
    }

    public function encrypt($txt, $key = '') {
        $this->key = $key ?: $this->key;
        srand(( double )microtime() * 1000000);
        $encrypt_key = md5(rand(0, 32000));
        $ctr = 0;
        $tmp = "";
        for ($i = 0; $i < strlen($txt); $i++) {
            if ($ctr == strlen($encrypt_key)) $ctr = 0;
            $tmp .= substr($encrypt_key, $ctr, 1) . (substr($txt, $i, 1) ^ substr($encrypt_key, $ctr, 1));
            $ctr++;
        }
        $_code = md5($encrypt_key) . base64_encode(self::keyED($tmp, $this->key)) . md5($encrypt_key . $this->key);
        return $_code;
    }


    public function decrypt($txt, $key = '') {
        $this->key = $key ?: $this->key;
        $txt = self::keyED(base64_decode(substr($txt, 32, -32)), $this->key);
        $tmp = "";
        for ($i = 0; $i < strlen($txt); $i++) {
            $md5 = substr($txt, $i, 1);
            $i++;
            $tmp .= (substr($txt, $i, 1) ^ $md5);
        }
        return $tmp;
    }


    public function setKey($key) {
        $this->key = $key;
        return $this;
    }

    public function getKey() {
        return $this->key;
    }
}